package com.dhl.fin.api.controller;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import com.dhl.fin.api.common.dto.ApiResponse;
import com.dhl.fin.api.common.util.DateUtil;
import com.dhl.fin.api.common.util.MapUtil;
import com.dhl.fin.api.common.util.WebUtil;
import com.dhl.fin.api.common.util.excel.ExcelSheet;
import com.dhl.fin.api.common.util.excel.ExcelUtil;
import com.dhl.fin.api.domain.*;
import com.dhl.fin.api.enums.ReportDataTypeEnum;
import com.dhl.fin.api.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author CuiJianbo
 * @since 2025/4/24
 */
@Transactional(rollbackFor = Exception.class)
@RestController
@RequestMapping("export")
public class ExportDataController {

    @Autowired
    private BankStatementService bankStatementService;

    @Autowired
    private BusinessRecordService businessRecordService;

    @Autowired
    private FixDepositService fixDepositService;

    @Autowired
    private BankAccountService bankAccountService;

    @Autowired
    private LendRecordService lendRecordService;


    @RequestMapping("recorddata")
    public void download(HttpServletResponse response, String yearmonth, Integer tabIndex) throws Exception {

        String faUnicode = WebUtil.getStringParam("faUnicode");
        String name = ReportDataTypeEnum.getByIndex(tabIndex).getName();
        String fileName = URLEncoder.encode(name, "UTF-8");
        String tableName = yearmonth + " " + name;
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);

        List<BankAccount> bankAccounts = bankAccountService.getAllBankAccountsByFamily(faUnicode);

        Class titleClass = null;
        List datas = null;
        List<ExcelSheet> excelSheets = new LinkedList<>();

        for (BankAccount bankAccount : bankAccounts) {
            Long bankAccountId = bankAccount.getId();
            if (name.equals(ReportDataTypeEnum.MONEY_RECORD.getName())) {
                datas = bankStatementService.queryBankStatement(yearmonth, bankAccountId);
                titleClass = BankStatement.class;
            } else if (name.equals(ReportDataTypeEnum.FIX_MONEY_RECORD.getName())) {
                datas = fixDepositService.queryFixDeposit(yearmonth, bankAccountId);
                titleClass = FixDeposit.class;
            } else if (name.equals(ReportDataTypeEnum.BUSINESS_MONEY_RECORD.getName())) {
                datas = businessRecordService.queryBusinessRecord(yearmonth, bankAccountId);
                titleClass = BusinessRecord.class;
            } else if (name.equals(ReportDataTypeEnum.LEND_OUT_RECORD.getName())) {
                datas = lendRecordService.queryLendRecord(yearmonth, bankAccountId);
                titleClass = LendRecord.class;
            }


            excelSheets.add(ExcelSheet.builder()
                    .setTitle(titleClass)
                    .setHeadName(tableName)
                    .setSheetName(bankAccount.getChildName())
                    .addRowList(datas)
                    .build());
        }


        ExcelUtil.builder()
                .addSheetAll(excelSheets)
                .build().writeToClient(response);


    }

    @ResponseBody
    @RequestMapping("tabs")
    public ApiResponse getTabs() throws Exception {
        List allTabsName = Arrays.stream(ReportDataTypeEnum.values()).sorted(
                Comparator.comparing(ReportDataTypeEnum::getIndex)
        ).map(ReportDataTypeEnum::getName).collect(Collectors.toList());
        DateTime startTime = cn.hutool.core.date.DateUtil.offset(DateUtil.getSysDate(), DateField.YEAR, -1);
        String familyCode = WebUtil.getStringParam("faUnicode");
        List<String> fixDepositYearMonth = fixDepositService.getFixDepositYearMonth(startTime,familyCode);
        List<String> businessRecordYearMonth = businessRecordService.getBusinessRecordYearMonth(startTime,familyCode);
        List<String> bankStatementYearMonth = bankStatementService.getBankStatementYearMonth(startTime,familyCode);
        List<String> lendRecordYearMonth = lendRecordService.getLendRecordYearMonth(startTime,familyCode);

        List<List<String>> data = new ArrayList<>();
        data.add(bankStatementYearMonth);
        data.add(fixDepositYearMonth);
        data.add(businessRecordYearMonth);
        data.add(lendRecordYearMonth);

        Map result = MapUtil.builder()
                .add("tabs", allTabsName)
                .add("tabBodyData", data)
                .build();

        return ApiResponse.success(result);
    }
}
